import React, { useEffect, useState, useRef } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import { motion } from 'framer-motion';
import { useAuth } from '../contexts/AuthContext';

const GoogleCallback: React.FC = () => {
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);
  const history = useHistory();
  const location = useLocation();
  const { loginWithGoogle, isAuthenticated } = useAuth();
  const processedRef = useRef(false);

  // 监听认证状态变化，登录成功后自动重定向
  useEffect(() => {
    if (isAuthenticated && success) {
      // 延迟跳转，让用户看到成功消息
      setTimeout(() => {
        history.push('/design-gallery');
      }, 1500);
    }
  }, [isAuthenticated, success, history]);

  useEffect(() => {
    const handleCallback = async () => {
      // 防止重复处理
      if (processedRef.current) {
        return;
      }
      processedRef.current = true;

      try {
        const urlParams = new URLSearchParams(location.search);
        const code = urlParams.get('code');
        const state = urlParams.get('state');
        const error = urlParams.get('error');
        const storedState = localStorage.getItem('oauth_state');

        // 清理存储的state
        localStorage.removeItem('oauth_state');

        if (error) {
          throw new Error(`Google returned an error: ${error}`);
        }

        if (!code) {
          throw new Error('No authorization code received from Google');
        }

        if (!state || state !== storedState) {
          throw new Error('Invalid state parameter - possible CSRF attack');
        }

        // 使用授权码登录
        await loginWithGoogle(code);

        setSuccess(true);
        setIsLoading(false);

      } catch (error: any) {
        console.error('Google OAuth callback error:', error);
        setError(error.message || 'Google login failed');
        setIsLoading(false);
      }
    };

    handleCallback();
  }, [location, history, loginWithGoogle]);

  const handleReturnToLogin = () => {
    history.push('/login');
  };

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <motion.div
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          className="bg-white p-8 rounded-lg shadow-lg text-center"
        >
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <h2 className="text-xl font-semibold text-gray-900 mb-2">Processing Google Login</h2>
          <p className="text-gray-600">Please wait while we complete your authentication...</p>
        </motion.div>
      </div>
    );
  }

  if (success) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <motion.div
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          className="bg-white p-8 rounded-lg shadow-lg text-center"
        >
          <div className="mx-auto h-12 w-12 text-green-600 mb-4">
            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
            </svg>
          </div>
          <h2 className="text-xl font-semibold text-gray-900 mb-2">Login Successful!</h2>
          <p className="text-gray-600 mb-4">You have been successfully logged in with Google.</p>
          <p className="text-sm text-gray-500">Redirecting to your profile...</p>
        </motion.div>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50">
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="bg-white p-8 rounded-lg shadow-lg text-center max-w-md w-full mx-4"
      >
        <div className="mx-auto h-12 w-12 text-red-600 mb-4">
          <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
          </svg>
        </div>
        <h2 className="text-xl font-semibold text-gray-900 mb-2">Login Failed</h2>
        <p className="text-gray-600 mb-6">{error}</p>
        <button
          onClick={handleReturnToLogin}
          className="w-full bg-blue-600 text-white py-2 px-4 rounded-lg hover:bg-blue-700 transition-colors"
        >
          Return to Login
        </button>
      </motion.div>
    </div>
  );
};

export default GoogleCallback;